package com.hyy.backend.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyy.backend.common.Result;
import com.hyy.backend.dao.CommentMapper;
import com.hyy.backend.dao.FavoriteMapper;
import com.hyy.backend.dao.KnowledgeMapper;
import com.hyy.backend.dao.UserMapper;
import com.hyy.backend.entity.Comment;
import com.hyy.backend.entity.Knowledge;
import com.hyy.backend.entity.UserInfo;
import com.hyy.backend.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private KnowledgeMapper knowledgeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired(required = false)
    private CommentMapper commentMapper;  // 可选

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    public Result<Map<String, Object>> getPostDetail(Integer id) {
        Knowledge post = knowledgeMapper.selectById(id);
        if (post == null || post.getIsDeleted() != null && post.getIsDeleted()) {
            return Result.error("帖子不存在或已删除");
        }

        UserInfo author = userMapper.selectById(post.getUserId());
        if (author == null) {
            return Result.error("作者信息未找到");
        }

        List<Comment> comments = commentMapper != null
                ? commentMapper.selectByPostId(id)
                : new ArrayList<>();

        // 查询当前所有收藏者
        List<String> favoritedBy = favoriteMapper.findUserIdsByPostId(id);




        Map<String, Object> data = new HashMap<>();
        data.put("post", post);
        data.put("author", author);
        data.put("nickname", author.getNickname()); // ✅ 添加昵称
        data.put("avatar", author.getAvatar());     // ✅ 添加头像
        data.put("comments", comments);

        data.put("favoritedBy", favoritedBy);
        data.put("favorites", favoritedBy.size());

        return Result.success(data);
    }

    @Override
    public Result<List<Map<String, Object>>> getAllPosts() {
        List<Knowledge> posts = knowledgeMapper.getAllVisiblePosts();
        List<Map<String, Object>> result = new ArrayList<>();

        Map<Integer, String> tagMap = getTagMap();

        for (Knowledge post : posts) {
            Map<String, Object> map = new HashMap<>();

            map.put("knowledgeId", post.getKnowledgeId());
            map.put("title", post.getTitle());
            map.put("content", post.getContent());
            map.put("createdAt", post.getCreatedAt());
            map.put("updatedAt", post.getUpdatedAt());
            map.put("postType", post.getPostType());

            // ✅ 标签解析
            map.put("tags", resolveTags(post.getTypeId(), tagMap));
            map.put("typeId", post.getTypeId());

            // ✅ 点赞、收藏
            String[] likedBy = post.getLikedBy() != null ? post.getLikedBy().split(",") : new String[0];
            map.put("likedBy", likedBy);
            map.put("likes", likedBy.length);

            List<String> favoritedBy = favoriteMapper.findUserIdsByPostId(post.getKnowledgeId());
            map.put("favoritedBy", favoritedBy);
            map.put("favorites", favoritedBy.size());

            // ✅ 评论数量
            int commentCount = commentMapper.countByPostId(post.getKnowledgeId());
            map.put("commentCount", commentCount);

            // ✅ 作者信息
            UserInfo user = userMapper.selectById(post.getUserId());
            map.put("author", user != null ? user.getNickname() : "匿名用户");
            map.put("avatar", user != null ? user.getAvatar() : null);
            map.put("userId", post.getUserId());

            result.add(map);
        }

        return Result.success(result);
    }


    private Map<Integer, String> getTagMap() {
        Map<Integer, String> map = new LinkedHashMap<>();
        map.put(1, "种植技术");
        map.put(2, "养殖技术");
        map.put(4, "农产品加工");
        map.put(8, "农业政策");
        map.put(16, "农机设备");
        map.put(32, "病虫害防治");
        return map;
    }

    @Override
    public Result<Map<String, Object>> likePost(Integer postId, Integer userId) {
        Knowledge post = knowledgeMapper.selectById(postId);
        if (post == null) return Result.error("帖子不存在");

        // 解析 liked_by 字符串为 Set<String>
        Set<String> likedBy = new HashSet<>();
        if (post.getLikedBy() != null && !post.getLikedBy().isEmpty()) {
            likedBy = new HashSet<>(Arrays.asList(post.getLikedBy().split(",")));
        }

        String userIdStr = String.valueOf(userId);
        boolean liked;

        if (likedBy.contains(userIdStr)) {
            likedBy.remove(userIdStr);
            post.setLikes(post.getLikes() - 1);
            liked = false;
        } else {
            likedBy.add(userIdStr);
            post.setLikes(post.getLikes() + 1);
            liked = true;
        }

        // 更新 liked_by 字段
        post.setLikedBy(String.join(",", likedBy));
        post.setLikes(likedBy.size()); // 使用 likedBy 大小更稳妥
        knowledgeMapper.updateById(post);

        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("liked", liked);
        result.put("likedBy", new ArrayList<>(likedBy)); // 转为 List<String> 便于 JSON 处理
        result.put("likes", likedBy.size());

        return Result.success(result);
    }

    @Override
    public Result<Map<String, Object>> favoritePost(Integer postId, Integer userId) {
        // 查询是否已收藏
        boolean hasFavorited = favoriteMapper.exists(postId, userId);

        if (hasFavorited) {
            favoriteMapper.remove(postId, userId);
        } else {
            favoriteMapper.add(postId, userId);
        }

        // 查询当前所有收藏者
        List<String> favoritedBy = favoriteMapper.findUserIdsByPostId(postId);

        Map<String, Object> result = new HashMap<>();
        result.put("favorited", !hasFavorited);
        result.put("favoritedBy", favoritedBy);
        result.put("favorites", favoritedBy.size());

        return Result.success(result);
    }
    private List<String> resolveTags(Integer typeId, Map<Integer, String> tagMap) {
        List<String> tags = new ArrayList<>();
        if (typeId == null) return tags;

        for (Map.Entry<Integer, String> entry : tagMap.entrySet()) {
            if ((typeId & entry.getKey()) != 0) {
                tags.add(entry.getValue());
            }
        }
        return tags;
    }

    @Override
    @Transactional  // 引入事务管理
    public Result<String> deletePostAndRelatedData(Integer postId) {
        Knowledge post = knowledgeMapper.selectById(postId);
        if (post == null || (post.getIsDeleted() != null && post.getIsDeleted())) {
            return Result.error("帖子不存在或已删除");
        }

        try {
            // 1. 删除评论
            commentMapper.deleteByKnowledgeId(postId);

            // 2. 删除收藏
            favoriteMapper.deleteByKnowledgeId(postId);

            // 3. 删除帖子记录（可选物理删除，当前为逻辑删除）
            post.setIsDeleted(true);
            knowledgeMapper.updateById(post);

            return Result.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }


}
